﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using System;

public class UI_Room : BaseUI
{
    public override UIConst UI_Type
    {
        get
        {
            return UIConst.UI_Room;
        }
    }

    public Button StartGameBtn, LeaveBtn;
    public GameObject playerItem_prefab;
    public Transform playerList_contatiner;
    public UI_RoomDetail ui_roomDetail;
    private List<UI_Room_PlayerItem> itemList = new List<UI_Room_PlayerItem>();


    private void Awake()
    {
        StartGameBtn.onClick.AddListener(OnStartGameBtn);
        LeaveBtn.onClick.AddListener(OnLeaveBtn);

     
    }
    
    private void OnLeaveRoom(EventObject msg)
    {
        var actor = (ActorData)msg.msgBody;
        SetUIData(RoomMgr.Instantce.curRoom);
    }
    private void OnOtherJoinRoom(EventObject msg)
    {
        var actor = (ActorData)msg.msgBody;
        SetUIData(RoomMgr.Instantce.curRoom);
    }

    private void OnDestroy()
    {
        
    }


    private void OnLeaveBtn()
    {
        RoomMgr.Instantce.QuitRoom();
        UIManager.Instantce.Close(this.UI_Type, this.ui_Id);
        UIManager.Instantce.Open(UIConst.UI_RoomList);
    }

    private void OnStartGameBtn()
    {
        RoomMgr.Instantce.SendStartGame();
    }

    public void SetUIData(RoomData room)
    {
        ui_roomDetail.SetUIData(room.map);

        for (int i = room.allPlayers.Count - 1; i < itemList.Count; i++)
        {
            itemList[i].gameObject.SetActive(false);
        }
        for (int i = 0; i < room.allPlayers.Count; i++)
        {
            UI_Room_PlayerItem item;
            if (i < itemList.Count)
            {
                item = itemList[i];
            }
            else
            {
                item = SpwanItem();
            }
            item.gameObject.SetActive(true);
            var uidata = room.allPlayers[i];
            item.SetUIData(uidata, room.readyList[i],() =>
            {
                Log.Info("Selet Player :" + uidata.ToString());
            });
        }
    }

    private UI_Room_PlayerItem SpwanItem()
    {
        var go = Instantiate(playerItem_prefab,playerList_contatiner);
        var item = go.GetComponent<UI_Room_PlayerItem>();
        itemList.Add(item);
        return item;
    }

    private void OnEnable()
    {
        SetUIData(RoomMgr.Instantce.curRoom);
        EventCentre.Instantce.AddEventListener(EventDefine.OnOtherJoinRoom, OnOtherJoinRoom);
        EventCentre.Instantce.AddEventListener(EventDefine.OnOtherLeaveRoom, OnLeaveRoom);
    }

    private void OnDisable()
    {
        EventCentre.Instantce.RemoveEvent(EventDefine.OnOtherJoinRoom, OnOtherJoinRoom);
        EventCentre.Instantce.RemoveEvent(EventDefine.OnOtherLeaveRoom, OnLeaveRoom);
    }
}

